package main

import (
	"context"
	"demo1/proto"
	"github.com/gin-gonic/gin"
	"github.com/micro/go-micro/v2/web"
	"github.com/micro/go-micro/v2/client"
	"io"
	"net/http"
)
/**
gin + go-micro 结合使用
 */
var cli proto.StudentService
func main(){
	engine := gin.Default()
	engine.GET("/user/:name",GetUser)
	engine.GET("/users",GetAllUser)
	server := web.NewService(
		web.Name("student-client"),
		web.Version("v1.0.0"),
		web.Handler(engine),//将路由处理自定义为engine
	)
	server.Init()
	//server.Handle("/",engine)
	cli = proto.NewStudentService("student.server",client.DefaultClient)
	if err := engine.Run();err!=nil{
		panic(err)
	}
}
func GetUser(ctx *gin.Context){
	name := ctx.Param("name")
	student,err := cli.GetStudent(context.Background(),&proto.StudentRequest{Name:name})
	if err!=nil{
		ctx.JSON(http.StatusOK,gin.H{"code":0,"data":"此学生不存在!","msg":"fail"})
	}else {
		ctx.JSON(http.StatusOK,gin.H{"code":1,"data":student,"msg":"success"})
	}
}
func GetAllUser(ctx *gin.Context){
	data,err := cli.GetAllStudent(context.Background(),&proto.StudentRequest{})
	if err!=nil{
		panic(err)
	}
	students :=[]proto.Student{}
	for {
		student,err:= data.Recv()
		if err == io.EOF{
			break
		}
		if err!=nil{
			break
		}
		students = append(students,*student)
	}
	data.Close()
	ctx.JSON(http.StatusOK,gin.H{"code":1,"data":students,"msg":"success"})
}